package com.org.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.org.common.PageBean;
import com.org.mapper.ServeMapper;
import com.org.pojo.*;
import com.org.service.NormalUserService;
import com.org.service.ServeService;
import com.org.utils.MapUtil;
import com.org.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * ClassName: ServeServiceImol
 * Package: com.org.service.impl
 * Description:
 *
 * @Author Origin
 * @Create 2024/2/6 13:51
 * @Version 1.0
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements ServeService {

    @Autowired
    private ServeMapper serveMapper;

    @Autowired
    private NormalUserService normalUserService;

    @Override
    public void add(Serve serve) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer communityId = (Integer) map.get("communityId");
        Integer createId = (Integer) map.get("id");
        Integer userType = (Integer) map.get("userType");

        serve.setUserType(userType);
        serve.setCreateId(createId);
        serve.setNumJoin(0);
        serve.setCommunityId(communityId);
//        long diffInMillis = cal2.getTimeInMillis()- cal1.getTimeInmillis(),
//        System.out.println(serve.getEndTime());
//        System.out.println(serve.getStartTime());
//        long time = Timestamp.valueOf(serve.getEndTime()).getTime() -
//                    Timestamp.valueOf(serve.getStartTime()).getTime();
//        Double diffInDays = time / (24.0*60*60*1000);
//        System.out.println(diffInDays);
//
//        serve.setDuration(diffInDays);
        serveMapper.add(serve);
    }

//    @Override
//    public PageBean<MyServeList> myServeList(Integer pageNum,
//                                             Integer pageSize,
//                                             String title,
//                                             String type,
//                                             String state) {
//        //1. 创建PageBean对象
//        PageBean<MyServeList> pb = new PageBean<>();
//
//        //2.开启分页查询
//        PageHelper.startPage(pageNum, pageSize);
//
//        Map<String, Object> map = ThreadLocalUtil.get();
//        Integer id = (Integer) map.get("id");
//        Integer userType = (Integer) map.get("userType");
////        System.out.println(userType);
//
//        //3.调用mapper
//        List<MyServeList> as = serveMapper.myServeList(title, type, state, userType, id);
//
//        //Page中提供了方法，可以获取PageHelper分页查询后 得到的总记录条数和当页数据
//        Page<MyServeList> p = (Page<MyServeList>) as;
//
//        //把数据填充到PageBean对象中
//        pb.setTotal(p.getTotal());  //总共多少页
//        pb.setItems(p.getResult()); //当前页内容
//
//        return pb;
//    }

    @Override
    public void update(Serve serve) {
        serve.setUpdateTime(LocalDateTime.now());
//        long time = Timestamp.valueOf(serve.getEndTime()).getTime() -
//                Timestamp.valueOf(serve.getStartTime()).getTime();
//        Double diffInDays = time / (24.0*60*60*1000);
//        System.out.println(diffInDays);
        serveMapper.update(serve);
    }

    @Override
    public Serve findById(Integer id) {
        Serve s = serveMapper.findById(id);
        return s;
    }

    @Override
    public void delete(Integer id) {
        serveMapper.deleteById(id);
    }

    @Override
    public void updateState(Integer id, String state) {
        serveMapper.updateState(id, state);
    }

    @Override
    public PageBean<Serve> allList(Integer pageNum,
                                   Integer pageSize,
                                   String location,
                                   String title,
                                   String content,
                                   String type,
                                   String userType,
                                   String createId,
                                   String communityId,
                                   String duration,
                                   String state,
                                   String removeDraftAndPending,
                                   String sortMethod) {
        //1. 创建PageBean对象
        PageBean<Serve> pb = new PageBean<>();

        //2.开启分页查询
        PageHelper.startPage(pageNum, pageSize);


        QueryWrapper<Serve> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("title", title)
                .like("content", content)
                .like("type", type)
                .like("state", state);

        if (!communityId.isEmpty()) {
            queryWrapper.eq("community_id", communityId);
        }

        if (!createId.isEmpty()) {
            queryWrapper.eq("create_id", createId);
        }

        if (!duration.isEmpty()) {
            queryWrapper.eq("duration", duration);
        }

        if (removeDraftAndPending != null){
            queryWrapper.ne("state", "草稿").ne("state", "待审核");
        }

        //3.调用mapper
        List<Serve> as = serveMapper.selectList(queryWrapper);

        // 更新每个skill的distance
        List<Serve> serves = MapUtil.setServeDistances(as, location);

        // 进行排序
        if (sortMethod != null && !sortMethod.isEmpty()){
            switch (sortMethod){
                case "距离最近":
                    serves.sort((o1, o2) -> Double.compare(o1.getDistance(), o2.getDistance()));
                    break;
                case "开始时间最近":
                    serves.sort((o1, o2) -> o1.getStartTime().compareTo(o2.getStartTime()));
                    break;
                case "最新发布":
                    serves.sort((o1, o2) -> o1.getCreateTime().compareTo(o2.getCreateTime()));
                    break;
            }
        }

        //Page中提供了方法，可以获取PageHelper分页查询后 得到的总记录条数和当页数据
        Page<Serve> p = (Page<Serve>) serves;

        //把数据填充到PageBean对象中
        pb.setTotal(p.getTotal());  //总共多少页
        pb.setItems(p.getResult()); //当前页内容

        return pb;
    }

    @Override
    public void refresh() {

        QueryWrapper<Serve> wrapper = new QueryWrapper<>();
        wrapper.or().eq("state", "进行中").or().eq("state", "已发布");
        // 查询操作
        List<Serve> l = serveMapper.selectList(wrapper);
        for (Serve s : l) {
            LocalDateTime startTime = s.getStartTime(); //判断当前服务状态
            LocalDateTime endTime = s.getEndTime();
            LocalDateTime now = LocalDateTime.now();

            if(startTime != null && endTime != null){   //空时间报错
                if (now.isAfter(startTime) && now.isBefore(endTime)) {
                    serveMapper.updateState(s.getId(), "进行中");
                } else if (now.isAfter(endTime)) {
                    serveMapper.updateState(s.getId(), "已完成");
                } else if (now.isBefore(startTime)) {
                    serveMapper.updateState(s.getId(), "已发布");
                }
            }
        }
    }

    @Override
    public Integer count(String title) {
        QueryWrapper<Serve> wrapper = new QueryWrapper<>();
        if (title.equals("已发布")) {

        }

        if (title.equals("历史")) {

        }
        return null;
    }
}
